package com.future.taskdemo.CompletionStage;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Dongwei-Chen
 * @Date 2023/5/22 8:55
 * @Description 协程测试
 */
public class StageTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

//        runAs();
    }

    private static void run1() {
        CompletableFuture.runAsync(() -> System.out.println("执行无返回结果的异步任务"));
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            CompletableFuture.supplyAsync(() -> {
                String result = "result:" + finalI;
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "  " + result);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return result;
            }, executorService).thenAccept((result) -> System.out.println(result));
        }
        System.out.println("主线程已经结束。。。。");
    }

    private static void run2() {

    }

    private static void runAs() throws ExecutionException, InterruptedException {
        CompletableFuture<Void> dddd = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(5000);
                System.out.println("dddd");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).thenApply((re) -> {
            return re;
        });
        System.out.println(dddd.get());
    }
}
